<template>
  <view class="my-nav-list" ref="navList">
    <view class="nav-list-box">
      <view
        class="nav-list-box-item"
        :class="{ active: navIndex === index }"
        @click="clickNav(item, index)"
        v-for="(item, index) in data"
        :key="item.label"
      >
        {{ item.label + (item.value ? "(" + item.value + ")" : "") }}</view
      >
      <view
        class="line"
        :style="[
          { width: width + 'px' },
          { left: left + wi * navIndex + 'px' },
        ]"
      ></view>
    </view>
  </view>
</template>
<script>
import { getSystemWi } from "@/store/user";
export default {
  props: {
    value: {
      type: Number,
      default: 0,
    },
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      navIndex: 0,
      width: 0,
      left: 0,
      wi: 0,
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.navIndex = val;
      },
    },
    data: {
      immediate: true,
      handler(val) {
        const that = this;
        that.$nextTick(() => {
          try {
            let info = uni
              .createSelectorQuery()
              .in(that)
              .select(".nav-list-box");
            info
              .boundingClientRect(function (data) {
                //	data - 包含元素的高度等信息
                const w = data.width;
                const wi = w / val.length;
                that.wi = wi;
                that.width = wi / 2;
                that.left = that.width / 2;
              })
              .exec(function (res) {
                // 注意：exec方法必须执行，即便什么也不做，否则不会获取到任何数据
              });
          } catch (error) {}
        });
      },
    },
  },
  mounted() {},
  methods: {
    clickNav(item, index) {
      this.navIndex = index;
      this.$emit("input", index);
      this.$emit("change", item, index);
    },
  },
};
</script>
<style lang="scss" scoped>
.my-nav-list {
  .nav-list-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    width: 100%;
    overflow: hidden;

    .nav-list-box-item {
      flex: 1;
      min-width: 120px;
      text-align: center;
      height: 70rpx;
      line-height: 80rpx;
      position: relative;
      white-space: nowrap;
    }

    .active {
      color: #5889f1;
      // &::after {
      //   content: "";
      //   position: absolute;
      //   bottom: 0;
      //   left: 0;
      //   height: 4rpx;
      //   width: 160rpx;
      //   background-color: #5889f1;
      // }
    }

    .line {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 4rpx;
      background-color: #5889f1;
      transition: all 0.3s;
    }
  }
}
</style>
